package com.sky.controller.admin;
/*
@author sun
@date 24/07/18
@project IntelliJ IDEA
*/

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

// 菜品管理
@RestController
@RequestMapping("/admin/dish")
@Slf4j
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;

    // 清理缓存数据
    public void cleanCache(String pattern){
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);

    }

    // 新增菜品 增1 或 n
    @PostMapping
    public Result addDishService(@RequestBody DishDTO dishDTO) {

        dishService.addDishWithFlavor(dishDTO);

        String key = "dish_" + dishDTO.getCategoryId();
        cleanCache(key);

        return Result.success();
    }

    // 菜品分页查询
    @GetMapping("/page")
    public Result<PageResult> pageQuery(DishPageQueryDTO dishPageQueryDTO){
        PageResult pageResult = dishService.pageQuery(dishPageQueryDTO);
        return Result.success(pageResult);
    }

    // 菜品批量删除  //将所有的菜品缓存数据清理掉，所有以dish_开头的key
    @DeleteMapping
    public Result delete(@RequestParam List<Long> ids){
        dishService.deleteList(ids);
        cleanCache("dish_*");
        return Result.success();
    }

    // 根据id查询菜品和对应的口味数据
    @GetMapping("/{id}")
    public Result<DishVO> getById(@PathVariable Long id){
        DishVO dishVO = dishService.getByIdWithFlavor(id);
        return Result.success(dishVO);
    }

    // 根据分类id查询菜品
    @GetMapping
    public Result<List<Dish>> queryCategoryById(@RequestParam Long categoryId){
        List<Dish> lists = dishService.queryCategoryById(categoryId);
        return Result.success(lists);
    }

    // 修改菜品
    @PutMapping
    public Result update(@RequestBody DishDTO dishDTO){
        dishService.updateDishWithFlavor(dishDTO);
        cleanCache("dish_*");
        return Result.success();
    }

    // 菜品起售停售
    @PostMapping("/status/{status}")
    public Result<String> startOrStop(@PathVariable Integer status,Long id){
        dishService.startOrStop(status,id);
        cleanCache("dish_*");
        return Result.success();
    }
}
